package com.lhb.service.serviceImpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lhb.dto.CourseAddDTO;
import com.lhb.dto.CourseEditDTO;
import com.lhb.dto.CoursePageQueryDTO;
import com.lhb.entity.Course;
import com.lhb.mapper.CourseMapper;
import com.lhb.result.PageResult;
import com.lhb.service.CourseService;
import com.lhb.vo.CoursePageQueryVO;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;


@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;


    /**
     * 课程分页查询
     * @param coursePageQueryDTO
     * @return
     */
    public PageResult pageQuery(CoursePageQueryDTO coursePageQueryDTO) {

        PageHelper.startPage(coursePageQueryDTO.getCurrentPage(), coursePageQueryDTO.getPageSize());

       Page<CoursePageQueryVO> page= courseMapper.pageQuery(coursePageQueryDTO);

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 添加课程成绩
     * @param courseAddDTO
     */
    public void add(CourseAddDTO courseAddDTO) {

        courseMapper.add(courseAddDTO);

    }

    /**
     * 编辑课程信息
     * @param courseEditDTO
     */
    public void edit(CourseEditDTO courseEditDTO) {


        courseMapper.edit(courseEditDTO);

    }

    /**
     * 删除课程
     * @param id
     */
    public void delete(Long id) {

        courseMapper.delete(id);
    }

    /**
     * 导出课程成绩
     * @param response
     */
    public void export(HttpServletResponse response, ArrayList<Course> list) {

        //1.通过POI将数据写入Excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/template.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件

            XSSFWorkbook excel = new XSSFWorkbook(in);


            //获取表格中的sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");


            for (int i = 2; i < list.size()+2; i++) {
                XSSFRow row = sheet.createRow(i);
                row.createCell(0).setCellValue(list.get(i-2).getStudentId());
                row.createCell(1).setCellValue(list.get(i-2).getCourseName());
                row.createCell(2).setCellValue(list.get(i-2).getCourseScore());
            }





            //3.通过输出流将Excel文件下载到客户端浏览器

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭资源

            outputStream.close();

            excel.close();
        }catch (IOException e) {
            e.printStackTrace();
        }

    }
}
